// pages/doctor/workbench/workbench.js
Page({
    data: {
        isLoading: true,
        // 欢迎语（根据时间变化）
        welcomeText: '',
        // 今日工作概览
        todayOverview: {
            appointments: 0,
            completed: 0,
            pending: 0,
            pendingFollowup: 0
        },
        // 待办提醒数据
        todoList: [],
        // 动态数据
        doctorInfo: null,
        recentPatients: [],
        stats: {},
        statistics: null,
        chartData: [],
        messageCount: 0,
        healthTips: null
    },

    // 获取医生信息（模拟API调用）
    getDoctorInfo: function () {
        return {
            name: '张医生',
            hospital: '口腔医院',
            department: '口腔科',
            avatar: '/images/doctor-avatar.png'
        };
    },

    // 获取最近患者列表（模拟API调用）
    getRecentPatients: function () {
        // 定义一些用于随机的颜色，让界面更丰富
        const avatarColors = ['#4fc3f7', '#66bb6a', '#ff7043', '#9575cd', '#ef5350'];

        return [
            {
                id: 1,
                name: '李先生',
                age: 35,
                gender: '男', // 新增字段
                department: '正畸科', // 新增字段
                condition: '牙齿美白',
                lastVisit: '2024-01-08',
                status: 'pending',
                statusText: '待接诊', // 新增字段，用于显示状态文本
                avatarText: '李', // 修正字段名：使用 avatarText
                avatarColor: avatarColors[Math.floor(Math.random() * avatarColors.length)] // 新增字段：随机背景色
            },
            {
                id: 2,
                name: '王女士',
                age: 28,
                gender: '女', // 新增字段
                department: '修复科', // 新增字段
                condition: '智齿拔除',
                lastVisit: '2024-01-07',
                status: 'ongoing',
                statusText: '治疗中', // 新增字段
                avatarText: '王', // 修正字段名
                avatarColor: avatarColors[Math.floor(Math.random() * avatarColors.length)] // 新增字段
            },
            {
                id: 3,
                name: '张先生',
                age: 42,
                gender: '男', // 新增字段
                department: '口腔内科', // 新增字段
                condition: '根管治疗',
                lastVisit: '2024-01-06',
                status: 'completed',
                statusText: '已完成', // 新增字段
                avatarText: '张', // 修正字段名
                avatarColor: avatarColors[Math.floor(Math.random() * avatarColors.length)] // 新增字段
            }
        ];
    },

    // 获取统计数据（模拟API调用）
    getStatistics: function () {
        return {
            totalPatients: 258,
            completedCases: 176,
            satisfactionRate: 96
        };
    },

    // 获取图表数据（模拟API调用）
    getChartData: function () {
        // 原始数据
        const rawData = [
            { label: '周一', value: 8 },
            { label: '周二', value: 12 },
            { label: '周三', value: 5 },
            { label: '周四', value: 9 },
            { label: '周五', value: 15 },
            { label: '周六', value: 7 },
            { label: '周日', value: 3 }
        ];

        // 在JS中预处理label，而不是在WXML中
        return rawData.map(item => ({
            ...item, // 复制原有属性
            label: item.label.slice(-1) // 将label处理为最后一个字
        }));
    },

    // 获取健康小贴士（模拟API调用）
    getHealthTips: function () {
        return {
            title: '今日健康提示',
            message: '建议在接诊后提醒患者正确刷牙方法，特别是正畸患者要使用专门的正畸牙刷，确保口腔清洁。'
        };
    },

    // 获取消息数量（模拟API调用）
    getMessageCount: function () {
        return 8;
    },

    onLoad: function (options) {
        // 页面加载时的初始化逻辑
        console.log('医生工作台页面加载');
        this.setWelcomeText();

        // 加载基础数据
        this.setData({
            doctorInfo: this.getDoctorInfo(),
            recentPatients: this.getRecentPatients(),
            statistics: this.getStatistics(),
            chartData: this.getChartData(),
            healthTips: this.getHealthTips(),
            messageCount: this.getMessageCount()
        });
    },

    // 🌟 核心改动：每次进入页面都重新加载仪表盘数据
    onShow: function () {
        console.log('医生工作台页面显示，开始刷新数据');
        // 调用数据加载函数，它会获取最新的待办数量
        this.loadDashboardData();
    },

    // 根据时间设置欢迎语
    setWelcomeText: function () {
        const hour = new Date().getHours();
        let text = '';

        if (hour < 12) {
            text = '上午好，祝您工作顺利！';
        } else if (hour < 18) {
            text = '下午好，加油工作！';
        } else {
            text = '晚上好，注意休息！';
        }

        this.setData({
            welcomeText: text
        });
    },

    onPullDownRefresh: function () {
        this.loadDashboardData(true);
    },

    loadDashboardData(isPullRefresh = false) {
        if (!isPullRefresh) {
            wx.showLoading({ title: '加载中...' });
        }

        this.fetchDashboardData()
            .then(res => {
                // 计算今日工作概览数据
                const totalAppointments = res.stats.today || 8;
                const completed = Math.floor(totalAppointments * 0.4);
                const pending = totalAppointments - completed;
                const pendingFollowup = res.todoList.find(item => item.id === 2)?.count || 0;

                // 修正：去掉字段映射，直接使用原始字段名（和 WXML 保持一致）
                const formattedTodoList = res.todoList.map(item => ({
                    id: item.id,
                    name: item.name, // 保持和 WXML 一致：item.name
                    count: item.count, // 保持和 WXML 一致：item.count
                    iconPath: item.iconPath, // 保持和 WXML 一致：item.iconPath
                    color: item.color, // 保持和 WXML 一致：item.color
                    path: item.path // 保持和 WXML 一致：item.path
                }));

                this.setData({
                    todoList: formattedTodoList, // 存入正确字段名的数据
                    stats: res.stats,
                    todayOverview: {
                        appointments: totalAppointments,
                        completed: completed,
                        pending: pending,
                        pendingFollowup: pendingFollowup
                    },
                    isLoading: false
                });

                // 更新图表数据
                this.updateChartData();
            })
            .catch(err => {
                this.setData({ isLoading: false });
                wx.showToast({ title: '加载失败', icon: 'none' });
                console.error('数据加载失败：', err);
            })
            .finally(() => {
                if (isPullRefresh) wx.stopPullDownRefresh();
                wx.hideLoading();
            });
    },

    fetchDashboardData() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                const mockData = {
                    todoList: [
                        { id: 1, name: '待接诊', iconPath: '/images/doctor/index/接诊.png', color: '#4fc3f7', count: 7, path: '/pages/doctor/appointment_management/appointment_management' },
                        { id: 2, name: '待复诊', iconPath: '/images/doctor/index/待复诊.png', color: '#66bb6a', count: 3, path: '/pages/doctor/appointment_management/appointment_management' },
                        { id: 3, name: '待处理', iconPath: '/images/doctor/index/待处理.png', color: '#ff7043', count: 2, path: '/pages/doctor/appointment_management/appointment_management' },
                    ],
                    stats: { today: 12, week: 36, total: 1280 }
                };

                if (Math.random() < 0.1) {
                    reject(new Error('模拟接口请求失败'));
                } else {
                    resolve(mockData);
                }
            }, 500);
        });
    },

    // 患者登记
    goToPatientRegister() {
        wx.navigateTo({
            url: '/pages/doctor/patient-register/patient-register',
        })
    },

    // 预约管理
    goToAppointmentManagement() {
        wx.switchTab({
            url: '/pages/doctor/appointment_management/appointment_management',
        })
    },

    // 患者档案
    goToPatientProfile() {
        wx.navigateTo({
            url: '/pages/doctor/patient-list/patient-list',
        })
    },

    // 病例管理
    goToCaseManagement() {
        wx.navigateTo({
            url: '/pages/doctor/case-management/case-management',
        })
    },

    // 诊疗记录
    goToTreatmentRecord() {
        wx.navigateTo({
            url: '/pages/doctor/treatment-record/treatment-record',
        })
    },

    // 数据统计
    goToDataStatistics() {
        wx.navigateTo({
            url: '/pages/doctor/data-statistics/data-statistics',
        })
    },

    goToToDo() {
        wx.navigateTo({
            url: '/pages/doctor/todo/todo',
        })
    },

    // 患者项点击事件处理
    onPatientItemTap: function (e) {
        const patientId = e.currentTarget.dataset.id;
        console.log('患者点击:', patientId);

        // 跳转到患者详情页
        wx.navigateTo({
            url: `/pages/doctor/patient-detail/patient-detail?id=${patientId}`
        });
    },

    // 消息图标点击事件
    goToMessages: function () {
        wx.navigateTo({
            url: '/pages/doctor/message/message'
        });
    },

    // 设置图标点击事件
    onSettingsTap: function () {
        wx.navigateTo({
            url: '/pages/doctor/settings/settings'
        });
    },

    // 工作概览项点击事件
    onOverviewItemTap: function (e) {
        const type = e.currentTarget.dataset.type;
        console.log('工作概览点击:', type);

        // 根据不同类型跳转到对应页面
        switch (type) {
            case 'appointments':
                wx.navigateTo({
                    url: '/pages/doctor/appointment/appointment?date=today'
                });
                break;
            case 'completed':
                wx.navigateTo({
                    url: '/pages/doctor/appointment/appointment?status=completed&date=today'
                });
                break;
            case 'pending':
                wx.navigateTo({
                    url: '/pages/doctor/appointment/appointment?status=pending&date=today'
                });
                break;
            case 'followup':
                wx.navigateTo({
                    url: '/pages/doctor/appointment/appointment?status=followup'
                });
                break;
        }
    },

    // 更新图表数据
    updateChartData: function () {
        // 生成随机的图表数据，基于今日预约数
        const baseValue = this.data.todayOverview.appointments || 8;
        const newChartData = this.getChartData().map(item => ({
            label: item.label,
            value: Math.floor(Math.random() * baseValue) + 2
        }));

        this.setData({
            chartData: newChartData
        });

        // 在真实场景中可以调用第三方图表库进行渲染
    },

    // 跳转更多患者页面
    onMorePatientsTap: function () {
        wx.navigateTo({
            url: '/pages/doctor/patient/patient'
        });
    },

    // 跳转更多统计页面
    onMoreStatisticsTap: function () {
        wx.navigateTo({
            url: '/pages/doctor/statistics/statistics'
        });
    }
});